﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Http;
using Newtonsoft.Json;
using System.Threading.Tasks;
using System.Windows.Forms;
using CefSharp;
using CefSharp.WinForms;
using DataFetchTool.Entity;


namespace DataFetchTool.Entity
{
    class ServerCommunicator
    {
        private string _host;
        public string Token { get; set; }
        public string ServerHost
        {
            get
            {
                return _host;
            }
            set
            {
                _host = value;
                if (value.EndsWith("/"))
                {
                    _host = _host.Substring(0, value.Length - 1);
                }
                if (_host.Contains(":"))
                {
                    var urlGroup = _host.Split(':');
                    _host = urlGroup[0];
                    if (int.TryParse(urlGroup[1], out int portResult))
                    {
                        Port = portResult;
                    }
                    else
                    {
                        Port = null;
                    }
                }
            }
        }
        public int? Port { get; set; }

        public string ServerUrl
        {
            get
            {
                if (Port != null)
                {
                    return $"http://{ServerHost}:{Port}";
                }
                else
                    return ServerHost;
            }
        }

        public Dictionary<string, FetchRules> Rules { get; private set; } = null;

        public void SetToken(string value)
        {
            this.Token = value;
        }

        public async void LoadRules(ChromiumWebBrowser Browser)
        {
            using (HttpClient client = new HttpClient())
            {
                try
                {
                    if (!string.IsNullOrEmpty(Token))
                    {
                        client.DefaultRequestHeaders.Add("Token", Token);
                    }
                    UriBuilder uriBuilder = new UriBuilder
                    {
                        Scheme = Properties.Resources.Schema,
                        Host = ServerHost,
                        Port = (int)(this.Port == null ? int.Parse(Properties.Resources.ServerPort) : this.Port),
                        Path = Properties.Resources.FetchRuleApiPath
                    };
                    HttpResponseMessage response = await client.GetAsync(uriBuilder.Uri);
                    response.EnsureSuccessStatusCode();
                    string responseBody = await response.Content.ReadAsStringAsync();
                    ServiceResponse<Dictionary<string, FetchRules>> responseObject = JsonConvert.DeserializeObject<ServiceResponse<Dictionary<string, FetchRules>>>(responseBody);
                    if (responseObject.code == 50002)
                    {
                        MessageBox.Show(responseObject.message, "提示");
                        Browser.Load($"{ServerUrl}/authpage/index.html");
                        return;
                    }
                    Rules = responseObject.data;
                }
                catch (AggregateException e)
                {
                    MessageBox.Show("获取采集规则失败: " + e.Message, "提示");
                }
                catch (HttpRequestException e)
                {
                    MessageBox.Show("获取采集规则失败: " + e.Message, "提示");
                }
            }

        }

        public async Task<string> PostTmallFetchData(string data, ChromiumWebBrowser Browser)
        {
            HttpClient client = new HttpClient();
            try
            {
                if (!string.IsNullOrEmpty(Token))
                {
                    client.DefaultRequestHeaders.Add("Token", Token);
                }
                UriBuilder uriBuilder = new UriBuilder
                {
                    Scheme = Properties.Resources.Schema,
                    Host = ServerHost,
                    Port = (int)(this.Port == null ? int.Parse(Properties.Resources.ServerPort) : this.Port),
                    Path = Properties.Resources.TmallApiPath
                };
                var content = new StringContent(data, Encoding.UTF8, "application/json");
                HttpResponseMessage response = await client.PostAsync(uriBuilder.Uri, content);
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
                ServiceResponse<object> responseObject = JsonConvert.DeserializeObject<ServiceResponse<object>>(responseBody);
                if (responseObject.code == 50002)
                {
                    Browser.Load($"{ServerUrl}/authpage/index.html");
                }
                return responseObject.message;
            }
            catch (AggregateException e)
            {
                return e.Message;
            }
            catch (HttpRequestException e)
            {
                return e.Message;
            }
        }

        public async Task<string> PostTaobaoFetchData(string data, ChromiumWebBrowser Browser)
        {
            HttpClient client = new HttpClient();
            try
            {
                if (!string.IsNullOrEmpty(Token))
                {
                    client.DefaultRequestHeaders.Add("Token", Token);
                }
                UriBuilder uriBuilder = new UriBuilder
                {
                    Scheme = Properties.Resources.Schema,
                    Host = ServerHost,
                    Port = (int)(this.Port == null ? int.Parse(Properties.Resources.ServerPort) : this.Port),
                    Path = Properties.Resources.TaobaoApiPath
                };
                var content = new StringContent(data, Encoding.UTF8, "application/json");
                HttpResponseMessage response = await client.PostAsync(uriBuilder.Uri, content);
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
                ServiceResponse<object> responseObject = JsonConvert.DeserializeObject<ServiceResponse<object>>(responseBody); if (responseObject.code == 50002)
                {
                    Browser.Load($"{ServerUrl}/authpage/index.html");
                }
                return responseObject.message;
            }
            catch (AggregateException e)
            {
                return e.Message;
            }
            catch (HttpRequestException e)
            {
                return e.Message;
            }
        }

        public async Task<string> ServerLifeCheck()
        {
            HttpClient client = new HttpClient();
            if (!string.IsNullOrEmpty(Token))
            {
                client.DefaultRequestHeaders.Add("Token", Token);
            }
            UriBuilder uriBuilder = new UriBuilder
            {
                Scheme = Properties.Resources.Schema,
                Host = ServerHost,
                Port = (int)(this.Port == null ? int.Parse(Properties.Resources.ServerPort) : this.Port),
                Path = Properties.Resources.LifeCheckApiPath
            };
            try
            {
                HttpResponseMessage response = await client.GetAsync(uriBuilder.Uri);
                response.EnsureSuccessStatusCode();
                return string.Empty;
            }
            catch (AggregateException e)
            {
                return e.Message;
            }
            catch (HttpRequestException)
            {
                return "服务未开启，无法提交数据";
            }
            catch (UriFormatException)
            {
                return "非法URI";
            }
        }
    }
}
